# coding: utf-8

from flask import Blueprint, request

from bluesky.dto.Response import Response
from bluesky.service.api import resource_service
from bluesky.util import biz

resource_blue = Blueprint('resource', __name__, url_prefix='/')
resource_blue.register_error_handler(Exception, biz.error_handler)


def close_session(request_ctx):
    session = request_ctx.get('session')
    if session:
        session.commit()
        session.close()


@resource_blue.route('/r/page/<rtype>/<key>', methods=['POST'])
def resource_page(rtype, key):
    data = request.get_json()
    request_ctx = biz.request_context(key)
    try:
        ctx = resource_service.search_resources(rtype, key, data, request_ctx)
        return Response.success_page(ctx.result)
    finally:
        close_session(request_ctx)


@resource_blue.route('/r/one/<rtype>/<action>', methods=['POST'])
def resource_one(rtype, action):
    data = request.get_json()
    request_ctx = biz.request_context(action)
    try:
        ctx = resource_service.search_one(rtype, action, data, request_ctx)
        return Response.success(ctx.result)
    finally:
        close_session(request_ctx)


@resource_blue.route('/r/detail/<rtype>/<rid>', methods=['POST'])
def resource_detail(rtype, rid):
    print(request.query_string)
    request_ctx = biz.request_context('get')
    try:
        ctx = resource_service.detail(rtype, rid, request_ctx)
        return Response.success(ctx.result)
    finally:
        close_session(request_ctx)


@resource_blue.route('/r/create/<rtype>', methods=['POST'])
def resource_create(rtype):
    data = request.get_json()
    request_ctx = biz.request_context('create')
    try:
        ctx = resource_service.create_resource(rtype, data, request_ctx)
        return Response.success(ctx.result)
    finally:
        close_session(request_ctx)


@resource_blue.route('/r/opr/<rtype>/<rid>/<action>', methods=['POST'])
def resource_opr(rtype, rid, action):
    data = request.get_json()
    request_ctx = biz.request_context(action)
    try:
        ctx = resource_service.opr_resource(rtype, rid, action, data, request_ctx)
        return Response.success(ctx.result)
    finally:
        close_session(request_ctx)


@resource_blue.route('/r/delete/<rtype>/<rid>', methods=['POST'])
def resource_delete(rtype, rid):
    data = request.get_json()
    action = 'delete'
    request_ctx = biz.request_context(action)
    try:
        ctx = resource_service.delete_resource(rtype, rid, action, data, request_ctx)
        return Response.success(ctx.result)
    finally:
        close_session(request_ctx)
